#include "Server/include/Server.h"
#define BUF_SIZE 2048

static void Server_accept(Server* self){
    while(true){
        printf("accept...\n");
        static struct epoll_event ev;
        ev.data.fd=accept(self->get_server_fd(),NULL,NULL);
        ev.events=EPOLLIN | EPOLLET |EPOLLOUT;
        if(epoll_ctl(self->get_epfd(),EPOLL_CTL_ADD,ev.data.fd,&ev)<0){
            printf("add epoll bad...\n");
        }
    }
}

int Server::run(){
    printf("run...\n");
    server_fd=socket(AF_INET,SOCK_STREAM,0);
    in_addr_t s;
    inet_pton(AF_INET,"127.0.0.1",(void*)&s);
    server_addr.sin_addr.s_addr=s;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(PORT);
    if(bind(server_fd,(sockaddr*)&server_addr,sizeof(server_addr))<0){
        printf("bind err...\n");
        return -1;
    }
    if(listen(server_fd,1024)<0){
        printf("listen err...\n");
        return -1;
    }

    std::thread t_accept(Server_accept,this);
    if(request()<0){
        return -1;
    }
    t_accept.join();
    return 0;
}

int test_sum=0;
int Server::request(){
    char buf[BUF_SIZE];
    while(1){
        int nfds=epoll_wait(epfd,events,5,-1);
        if(nfds<0){
            printf("epoll_wait error...[%d][%s]\n",nfds,strerror(errno));
            abort();
            return -1;
        }
        // RequestHead rhead;
        for(int i=0;i<nfds;i++){
            memset(buf,0,sizeof(buf));
            int tmp_epoll_fd=events[i].data.fd;
            read(tmp_epoll_fd,buf,sizeof(buf));
            std::shared_ptr<RequestHead> rhead(new(std::nothrow) RequestHead);
            add(buf,sizeof(buf),rhead);
            std::shared_ptr<HTTP> http(new(std::nothrow) HTTP(tmp_epoll_fd,epfd,&events[i]));
            http->reuqest(rhead);
            printf("%d次请求\n",++test_sum);
        }
    }
    return 0;
}